package sjtu.ist.warehouse4ws.action;

import java.io.PrintWriter;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;

import sjtu.ist.warehouse4ws.model.ShiroRole;
import sjtu.ist.warehouse4ws.model.ShiroUser;
import sjtu.ist.warehouse4ws.service.ShiroUserService;
import sjtu.ist.warehouse4ws.tool.BaseAction;

import com.opensymphony.xwork2.ActionContext;
public class LoginAction extends BaseAction {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1246131239446241208L;

	private String userName;
	private String password;
	private String randCode;
	private boolean success;
	private String message;
	private boolean rememberMe=true;
	private ShiroUserService shiroUserService;
	private String upload;



	public void setShiroUserService(ShiroUserService shiroUserService) {
		this.shiroUserService = shiroUserService;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public boolean isSuccess() {
		  return success;
	}
	public void setSuccess(boolean success) {
		  this.success = success;
	}
	public String getMessage() {
		return message;
	}
	public void setMessage(String message) {
		this.message = message;
	}
	//处理用户请求的execute方法
	public String execute() throws Exception {
	
		String sessionId=ServletActionContext.getRequest().getSession().getId();
		System.out.println("Login:"+sessionId);
		
		UsernamePasswordToken token = new UsernamePasswordToken(userName,
				password, rememberMe);
		try {
			Subject currentUser = SecurityUtils.getSubject();
			
			if (!currentUser.isAuthenticated()) {
				
				this.message="/WareHouse4WS"+"/mainload";
				//this.message="/WareHouse4WS"+"/mainload";                 //非插件上传 有问题
				this.success=true;
				ShiroUser user=shiroUserService.findUser(userName);
				for(ShiroRole role:user.getShiroRoles()){
					currentUser.getSession().setAttribute("role", role.getRolename());
				}
				currentUser.getSession().setAttribute("companyId", user.getCompanyId());
				currentUser.getSession().setAttribute("userId", user.getUserId());
				currentUser.getSession().setAttribute("username", user.getUsername());	
				currentUser.login(token);
				
				ActionContext ac=ActionContext.getContext();
				Map<String,Object> session=ac.getSession();
				
				session.put("upload", upload);
				
				session.put("user", user);
				session.put("username", user.getUsername());
				if(currentUser.hasRole("superadmin")){
					session.put("superadmin", "superadmin");
				}else{
					session.put("companyId", user.getCompanyId());
				}
				
				if(upload!=null && upload.equals("1")){
					//this.getResponse().sendRedirect("http://127.0.0.1:8080"+"/WareHouse4WS"+"/mainload");
					this.getResponse().sendRedirect("/WareHouse4WS"+"/mainload");
				}
			}else{
				ActionContext ac=ActionContext.getContext();
				Map<String,Object> session=ac.getSession();
				
				session.put("upload", upload);
				
				if(upload!=null && upload.equals("1")){
					//this.getResponse().sendRedirect("http://127.0.0.1:8080"+"/WareHouse4WS"+"/mainload");
					this.getResponse().sendRedirect("/WareHouse4WS"+"/mainload");
				}
				//this.message="http://127.0.0.1:8080"+"/WareHouse4WS"+"/mainload";
				this.message="/WareHouse4WS"+"/mainload";                 //非插件上传 有问题
				this.success=true;
			}
		} catch (UnknownAccountException uae) {
			System.out.println(uae.toString());
			addFieldError("userName", "未知帐号");
			this.message="未知帐号";
			this.success=false;
		} catch (IncorrectCredentialsException ice) {
			System.out.println(ice.toString());
			addFieldError("userName", "密码错误或帐号错误");
			this.message="密码错误或帐号错误";
			this.success=false;
		} catch (LockedAccountException lae) {
			System.out.println(lae.toString());
			this.message="帐号锁异常";
			this.success=false;
		} catch (ExcessiveAttemptsException eae) {
			addFieldError("userName", "超过尝试次数");
			System.out.println(eae.toString());
			this.message="超过尝试次数";
			this.success=false;
		} catch (AuthenticationException e) {
			System.out.println(e.toString());

			addFieldError("userName", "登录失败");
			this.message="登录失败";
			this.success=false;
		}
		return SUCCESS;
	}
	/**
	 * @param upload the upload to set
	 */
	public void setUpload(String upload) {
		this.upload = upload;
	}
	/**
	 * @return the upload
	 */
	public String getUpload() {
		return upload;
	}
}
